#include "mainwindow.h"
#include "ui_mainwindow.h"

#include "observerwidget.h"

#include <QMouseEvent>
#include <QPainter>
#include <QDebug>



MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QObject::connect(ui->actionNew_Widget, &QAction::triggered, this, &MainWindow::newWidget);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::mousePressEvent(QMouseEvent *event)
{
     mousePressPoint =  event->pos();
}

void MainWindow::mouseReleaseEvent(QMouseEvent *event)
{
    mouseReleasePoint = event->pos();
    update();

    notify();

}

void MainWindow::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    painter.drawLine(mousePressPoint, mouseReleasePoint);
}


void MainWindow::newWidget()
{
    ObserverWidget * widget = new ObserverWidget(this);
    attach(widget);
    widget->setMinimumSize(size());
    widget->show();
}


void MainWindow::attach(ObserverBase *obj)
{
    listView.append(obj);
}

void MainWindow::detach(ObserverBase *obj)
{
    listView.removeOne(obj);
}

void MainWindow::notify()
{
    for (auto &item : listView)
    {
        item->updateValue(mousePressPoint, mouseReleasePoint);
    }
}
